/**
 * Project Name:jiuselu-parent
 * File Name:OrderController.java
 * Package Name:com.fxp.project.jiuselu.web.business.v1.controller.order
 * Date:2021年11月17日 15:16
 * Copyright (c) 2021, Kai.Wang All Rights Reserved.
 */
package com.fxp.project.jiuselu.web.business.v1.controller.order;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fxp.project.express.entity.request.QueryTrackParam;
import com.fxp.project.express.entity.response.QueryTrackData;
import com.fxp.project.express.entity.response.QueryTrackResp;
import com.fxp.project.express.service.impl.QueryTrackService;
import com.fxp.project.jiuselu.commons.constant.ConstantCode;
import com.fxp.project.jiuselu.commons.exceptions.ParamException;
import com.fxp.project.jiuselu.web.base.controller.BaseController;
import com.fxp.project.jiuselu.web.base.request.ReqBase;
import com.fxp.project.jiuselu.web.business.v1.request.base.ReqBasePage;
import com.fxp.project.jiuselu.web.business.v1.request.order.*;
import com.fxp.project.jiuselu.web.constant.Constants;
import com.fxp.project.jiuselu.web.domain.CommonPage;
import com.fxp.project.jiuselu.web.domain.CommonResult;
import com.fxp.project.jiuselu.web.models.common.service.IJslLogisticCompanyService;
import com.fxp.project.jiuselu.web.models.coupon.entity.JslUserCoupon;
import com.fxp.project.jiuselu.web.models.coupon.service.IJslUserCouponService;
import com.fxp.project.jiuselu.web.models.fare.entity.JslUserFareApplied;
import com.fxp.project.jiuselu.web.models.fare.entity.JslUserFareOrderApply;
import com.fxp.project.jiuselu.web.models.fare.mapper.JslUserFareOrderApplyMapper;
import com.fxp.project.jiuselu.web.models.fare.service.IJslUserFareAppliedService;
import com.fxp.project.jiuselu.web.models.fare.service.IJslUserFareOrderApplyService;
import com.fxp.project.jiuselu.web.models.order.entity.JslOrder;
import com.fxp.project.jiuselu.web.models.order.entity.JslOrderArrears;
import com.fxp.project.jiuselu.web.models.order.entity.JslOrderSample;
import com.fxp.project.jiuselu.web.models.order.entity.SplitOrder;
import com.fxp.project.jiuselu.web.models.order.mapper.JslOrderMapper;
import com.fxp.project.jiuselu.web.models.order.service.*;
import com.fxp.project.jiuselu.web.models.order.vo.JslOrderArrearsVo;
import com.fxp.project.jiuselu.web.models.order.vo.JslOrderVo;
import com.fxp.project.jiuselu.web.models.order.vo.OrderStatusVo;
import com.fxp.project.jiuselu.web.models.payimage.entity.PayImg;
import com.fxp.project.jiuselu.web.models.payimage.service.IPayImgService;
import com.fxp.project.jiuselu.web.models.sample.entity.vo.SampleOrderVo;
import com.fxp.project.jiuselu.web.models.sample.service.ISampleOrderService;
import com.fxp.project.jiuselu.web.models.user.entity.JslUser;
import com.fxp.project.jiuselu.web.models.user.entity.JslUserExtend;
import com.fxp.project.jiuselu.web.models.user.service.IJslUserService;
import com.fxp.project.jiuselu.web.models.user.service.impl.JslUserServiceImpl;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

/**
 * ClassName:OrderController<br/>
 * Function: 用户订单控制器<br/>
 * Date:2021年11月17日 15:16<br/>
 *
 * @author Kai.Wang
 * @version 1.0.0
 * @see
 * @since JDK 8
 */
@Log4j2
@RestController
@RequestMapping("/v1/order")
@Transactional
public class OrderController extends BaseController {

    @Autowired
    IJslOrderService jslOrderService;
    @Autowired
    IJslOrderSampleService jslOrderSampleService;
    @Autowired
    IJslOrderArrearsService jslOrderArrearsService;
    @Autowired
    QueryTrackService queryTrackService;
    @Autowired
    IJslLogisticCompanyService jslLogisticCompanyService;
    @Autowired
    private JslOrderMapper jslOrderMapper;
    @Autowired
    private IJslUserService jslUserService;
    @Autowired
    private IJslUserCouponService jslUserCouponService;
    @Autowired
    private ISampleOrderService sampleOrderService;
    @Autowired
    private ISplitOrderService splitOrderService;
    @Autowired
    JslUserFareOrderApplyMapper jslUserFareOrderApplyMapper;
    @Autowired
    IPayImgService payImgService;


    /**
     * list: 用户的订单列表<br/>
     *
     * @param reqOrderList
     * @param result
     * @return
     * @author Kai.Wang
     * @date 2021/11/24 13:27
     */
    @PostMapping("list")
    @CrossOrigin
    public CommonResult list(@RequestBody @Validated ReqOrderList reqOrderList, BindingResult result) {
        super.checkBindResult(result);
        LocalDateTime currentDate = super.setPageQueryTag(Constants.USER_ORDER_NORMAL_LIST_CODE, reqOrderList.getPage(), super.getCurrentUserInfo().getUserId());
        PageInfo<?> pageInfo = jslOrderService.selectJslOrderVoByUserId(reqOrderList.getPage(), reqOrderList.getSize(), currentDate, super.getCurrentUserInfo().getUserId(), reqOrderList.getOrderTotalStatus());
        return CommonResult.success(CommonPage.restPage(pageInfo));
    }

    /**
     * list: 用户的没开票订单列表<br/>
     *
     * @param reqOrderList
     * @param result
     * @return
     * @author Kai.Wang
     * @date 2021/11/24 13:27
     */
    @PostMapping("/fare/list")
    @CrossOrigin
    public CommonResult Farelist(@RequestBody @Validated ReqOrderList reqOrderList, BindingResult result) {
        super.checkBindResult(result);
        LocalDateTime currentDate = super.setPageQueryTag(Constants.USER_ORDER_NORMAL_LIST_CODE, reqOrderList.getPage(), super.getCurrentUserInfo().getUserId());
        PageInfo<?> pageInfo = jslOrderService.selectFareJslOrderVoByUserId(reqOrderList.getPagenum(), reqOrderList.getPagesize(), currentDate, super.getCurrentUserInfo().getUserId(), reqOrderList.getOrderTotalStatus());
        return CommonResult.success(CommonPage.restPage(pageInfo));
    }

    /**
     * reserveList: 预定订单列表<br/>
     *
     * @param reqOrderList
     * @param result
     * @return
     * @author Kai.Wang
     * @date 2021/11/24 14:49
     */
    @PostMapping("reserve/list")
    @CrossOrigin
    public CommonResult reserveList(@RequestBody @Validated ReqOrderList reqOrderList, BindingResult result) {
        super.checkBindResult(result);
        LocalDateTime currentDate = super.setPageQueryTag(Constants.USER_ORDER_RESERVE_LIST_CODE, reqOrderList.getPage(), super.getCurrentUserInfo().getUserId());
        PageInfo<?> pageInfo = jslOrderService.selectJslOrderArrearsVoByUserId(reqOrderList.getPage(), reqOrderList.getSize(), currentDate, super.getCurrentUserInfo().getUserId(), reqOrderList.getOrderTotalStatus());
        return CommonResult.success(pageInfo);
    }


    /**
     * 删除订单
     */
    @PostMapping("/removeOrder")
    @CrossOrigin
    public CommonResult removeOrder(String orderId) {
        return CommonResult.success(jslOrderMapper.deleteOrderByOrderId(orderId));
    }


    /**
     * 订单列表+未付款订单失效时间
     *
     * @param userId 登陆者用户id
     * @return
     */
    @PostMapping("/time/{userId}/{orderTotalStatus}")
    @CrossOrigin
    public CommonResult getOrder(@PathVariable("userId") Long userId, @PathVariable("orderTotalStatus") Integer orderTotalStatus) {
        LocalDateTime time = LocalDateTime.now();
        List<JslOrderVo> jslOrderVo = jslOrderService.selectJslOrderByUserId(userId, time, orderTotalStatus);
        for (JslOrderVo s : jslOrderVo) {
            if (s.getPayStatus() == 0) {
                long surplusMills = s.getAddTime().toEpochSecond(ZoneOffset.of("+8")) + 604800  - LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
                s.setSurplusMills(surplusMills);
                if (surplusMills <= 0 && s.getCancelStatus() == null) {
                    jslOrderService.updateStatus(s.getOrderId());
                    jslUserCouponService.updateCouponStatus(s.getOrderId());
                }
            }
        }
        return CommonResult.success(jslOrderVo);
    }

    /**
     * 全款订单订单列表+未付款订单失效时间
     *
     * @param userId 登陆者用户id
     * @return
     */
    @PostMapping("/total/{userId}/{orderTotalStatus}")
    @CrossOrigin
    public CommonResult getOrdertime(@PathVariable("userId") Long userId, @PathVariable("orderTotalStatus") Integer orderTotalStatus) {
        LocalDateTime time = LocalDateTime.now();
        List<JslOrderVo> jslOrderVo = jslOrderService.selectTotalOrderByUserId(userId, time, orderTotalStatus);

        for (JslOrderVo s : jslOrderVo) {
            PayImg payImg=new PayImg();
            payImg.setOrderId(s.getOrderId());
            List<PayImg> payImgs = payImgService.selectPayImgList(payImg);
            if ((payImgs.size() > 0)) { s.setIsUpload(true); } else { s.setIsUpload(false); }
            if (s.getPayStatus() == 0) {
                long surplusMills = s.getAddTime().toEpochSecond(ZoneOffset.of("+8")) + 604800  - LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
                s.setSurplusMills(surplusMills);
                if (surplusMills <= 0 && s.getCancelStatus() == null) {
                    jslUserCouponService.selectJslUserCouponByOrderId(s.getCouponPrice(),s.getOrderId());
                    jslOrderService.updateStatus(s.getOrderId());
                    jslUserCouponService.updateCouponStatus(s.getOrderId());
                }
            }
            if (s.getLogisticStatus() == 1 && s.getOrderStatus() == 0) {
                if (s.getLogisticTime() != null) {
                    long surplusMills = s.getLogisticTime().toEpochSecond(ZoneOffset.of("+8")) + 1209600 - LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
                    JslOrderVo jslOrderVo1 = jslOrderService.selectJslOrderVoByOrderId(s.getOrderId());

                    if (surplusMills <= 0 && jslOrderVo1.getOrderStatus()!=1 && jslOrderVo1.getIsDelay()!=2) {
                        jslOrderVo1.setOrderStatus(1);
                        jslOrderVo1.setIsDelay(2);
                        jslOrderService.updateById(jslOrderVo1);
                    }
                    s.setIsDelayTime(surplusMills);
                }
            }
        }
        return CommonResult.success(jslOrderVo);
    }

    /**
     * 银行转账订单,分类
     *
     * @param userId
     * @param orderTotalStatus
     * @return
     */
    @PostMapping("/bank/{userId}/{orderTotalStatus}")
    @CrossOrigin
    public CommonResult bankOrder(@PathVariable("userId") Long userId, @PathVariable("orderTotalStatus") Integer orderTotalStatus) {
        LocalDateTime time = LocalDateTime.now();
        List<JslOrderVo> jslOrderVo = jslOrderService.selectBankOrderByUserId(userId, time, orderTotalStatus);
        for (JslOrderVo s : jslOrderVo) {
            if (s.getPayStatus() == 0) {
                long surplusMills = s.getAddTime().toEpochSecond(ZoneOffset.of("+8")) + 604800 - LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
                s.setSurplusMills(surplusMills);
                if (surplusMills <= 0 && s.getCancelStatus() == null) {
                    jslOrderService.updateStatus(s.getOrderId());
                    jslUserCouponService.updateCouponStatus(s.getOrderId());
                }
            }
        }
        return CommonResult.success(jslOrderVo);
    }


    /**
     * 银行承兑点
     *
     * @return
     */
    @GetMapping("ordertax")
    @CrossOrigin
    public CommonResult getTax() {
        BigDecimal jslTax = jslOrderService.getJslTax();
        return CommonResult.success(jslTax);
    }

    /**
     * bankList: 银行承兑订单<br/>
     *
     * @param reqOrderList
     * @param result
     * @return
     * @author Kai.Wang
     * @date 2021/11/24 14:51
     */
    @PostMapping("bank/list")
    @CrossOrigin
    public CommonResult bankList(@RequestBody @Validated ReqOrderList reqOrderList, BindingResult result) {
        super.checkBindResult(result);
        LocalDateTime currentDate = super.setPageQueryTag(Constants.USER_ORDER_BANK_LIST_CODE, reqOrderList.getPage(), super.getCurrentUserInfo().getUserId());
        PageInfo<?> pageInfo = jslOrderService.selectJslOrderVoByUserIdForBank(reqOrderList.getPage(), reqOrderList.getSize(), currentDate, super.getCurrentUserInfo().getUserId());
        return CommonResult.success(CommonPage.restPage(pageInfo));
    }

    /**
     * submit: 订单提交<br/>
     *
     * @param reqOrderCart
     * @param result
     * @return
     * @author Kai.Wang
     * @date 2021/11/18 10:55
     */
    @PostMapping("submit")
    @CrossOrigin
    public CommonResult submit(@RequestBody @Validated ReqOrderCart reqOrderCart, BindingResult result) {
        super.checkBindResult(result);
        return CommonResult.success(jslOrderService.saveUserOrderByUserId(reqOrderCart, super.getCurrentUserInfo().getUserId()));
    }

    /**
     * quickly: 立即购买<br/>
     *
     * @param reqOrderQuickly
     * @param result
     * @return
     * @author Kai.Wang
     * @date 2021/11/23 15:27
     */
    @PostMapping("/quickly")
    @CrossOrigin
    public CommonResult quickly(@RequestBody @Validated ReqOrderQuickly reqOrderQuickly, BindingResult result) {
        super.checkBindResult(result);
        return CommonResult.success(jslOrderService.saveUserQuicklyOrderByUserId(reqOrderQuickly, super.getCurrentUserInfo().getUserId()));
    }

    /**
     * sample: 来样定制订单<br/>
     *
     * @param reqOrderSample
     * @param result
     * @return
     * @author Kai.Wang
     * @date 2021/11/23 18:12
     */
    @PostMapping("sample")
    @CrossOrigin
    public CommonResult sample(@RequestBody @Validated ReqOrderSample reqOrderSample, BindingResult result) {
        super.checkBindResult(result);
        return CommonResult.success(jslOrderSampleService.saveOrderSampleByUserId(reqOrderSample, super.getCurrentUserInfo().getUserId()));
    }

    /**
     * sampleList: 样品订单历史<br/>
     *
     * @param reqBasePage
     * @param result
     * @return
     * @author Kai.Wang
     * @date 2021/11/23 18:31
     */
    @PostMapping("sample/list")
    @CrossOrigin
    public CommonResult sampleList(@RequestBody @Validated ReqBasePage reqBasePage, BindingResult result) {
        super.checkBindResult(result);
        QueryWrapper<JslOrderSample> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", super.getCurrentUserInfo().getUserId()).orderByDesc("create_time");

        return CommonResult.success(jslOrderSampleService.list(queryWrapper));
    }

    /**
     * sampleDetail: 样品订单详情<br/>
     *
     * @param sampleSn
     * @param reqBase
     * @param result
     * @return
     * @author Kai.Wang
     * @date 2021/11/23 18:29
     */
    @PostMapping("sample/detail/{sampleSn}")
    @CrossOrigin
    public CommonResult sampleDetail(@PathVariable("sampleSn") String sampleSn, @RequestBody @Validated ReqBase reqBase, BindingResult result) {
        return CommonResult.success(jslOrderSampleService.selectOrderSampleBylogisticOrder(sampleSn));
    }


    /**
     * orderDetail: 查询当前订单详情<br/>
     *
     * @param reqOrderDetail
     * @param result
     * @return
     * @author Jason.Wang
     * @date 2021/12/26 12:06
     */
    @PostMapping("detail")
    @CrossOrigin
    public CommonResult orderDetail(@RequestBody @Validated ReqOrderDetail reqOrderDetail, BindingResult result) throws Exception {

        Long userId;
//        if (reqOrderDetail.getUserId()!=null) {
//            try {

        String orderId = reqOrderDetail.getOrderId();

        if (!orderId.contains("LX")) {
            if (orderId.length() != 25) {
                orderId = orderId.substring(0, orderId.length() - 1);
            }
        }

        userId = jslOrderService.getById(orderId).getUserId();
//            }catch (Exception e){
//                return CommonResult.failed("未查询到对应订单");
//            }
//
//        }else {
//            userId=super.getCurrentUserInfo().getUserId();
//        }


        super.checkBindResult(result);
        JslOrderVo jslOrderVo = jslOrderService.selectJslOrderVoByUserIdAndOrderId(orderId, userId);
//        String orderId=reqOrderDetail.getOrderId().substring(0,reqOrderDetail.getOrderId().length()-1);
//        JslOrderVo jslOrderVo = jslOrderMapper.selectJslOrderVoByOrderId(orderId);

        QueryWrapper<JslOrderArrears> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", jslOrderVo.getOrderId());
        queryWrapper.orderByAsc("create_time");
        List<JslOrderArrears> jslOrderArrears = jslOrderArrearsService.list(queryWrapper);


        List<QueryTrackData> express = new ArrayList<>();
        // 判断当前是否存在物流信息
        if (jslOrderVo.getLogisticStatus() == 1) {
            QueryTrackParam queryTrackParam = QueryTrackParam.builder().com(jslOrderVo.getLogisticCode()).num(jslOrderVo.getLogisticNum()).phone(jslOrderVo.getPhone()).build();
            QueryTrackResp queryTrackResp = null;
            try {
                queryTrackResp = queryTrackService.queryTrack(queryTrackParam);
                if ("ok".equalsIgnoreCase(queryTrackResp.getMessage()) && "200".equals(queryTrackResp.getStatus())) {
                    express = queryTrackResp.getData();
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error(e);
            }
        }
        JSONObject data = new JSONObject();
        data.put("order", jslOrderVo);
        data.put("express", express);
        data.put("payment", jslOrderArrears);
        if (jslOrderVo.getPayStatus() == 0) {
            long surplusMills = jslOrderVo.getAddTime().toEpochSecond(ZoneOffset.of("+8")) + 604800 - LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
            System.out.println("surplusMills--------->" + surplusMills);
            data.put("surplusMills", surplusMills);
        }
        //自动确认收获 && 延长收货
        if (jslOrderVo.getLogisticStatus() == 1) {
            SplitOrder splitOrder = splitOrderService.selectSplitOrderByOrderId(orderId);
            if(splitOrder !=null){
                long isDelayTime = splitOrder.getCreateTime().toEpochSecond(ZoneOffset.of("+8")) + 604800 - LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
                Optional.ofNullable(splitOrder.getId()).orElseThrow(()->new Exception("该订单暂无物流信息"));
                //判断是否点击延长收货
                if (jslOrderVo.getIsDelay() == 1) {
                    isDelayTime = isDelayTime + 604800;
                    //判断是否已超过延长收货时间,超过则修改订单状态
                    if(isDelayTime <= 0){
                        JslOrder jslOrder = new JslOrder();
                        jslOrder.setOrderStatus(1);
                        jslOrder.setIsDelay(2);
                        jslOrderMapper.updateById(jslOrder);
                    }
                }
                System.out.println(isDelayTime);
                data.put("isDelayTime", isDelayTime);
            }

        }
        return CommonResult.success(data);
    }

    /**
     * orderDetail: 查询当前订单详情<br/>
     *
     * @param reqOrderDetail
     * @param result
     * @return
     * @author Jason.Wang
     * @date 2021/12/26 12:06
     */
    @PostMapping("sampleDetail")
    @CrossOrigin
    public CommonResult sampleDetail(@RequestBody @Validated ReqOrderDetail reqOrderDetail, BindingResult result) {

        Long userId;
//        if (reqOrderDetail.getUserId()!=null) {
//            try {
        String orderId = reqOrderDetail.getOrderId();

        if (!orderId.contains("LX")) {
            if (orderId.length() != 25) {
                orderId = orderId.substring(0, orderId.length() - 1);
            }
        }
//        userId = jslOrderService.getById(orderId).getUserId();
//            }catch (Exception e){
//                return CommonResult.failed("未查询到对应订单");
//            }
//
//        }else {
//            userId=super.getCurrentUserInfo().getUserId();
//        }
        super.checkBindResult(result);
        SampleOrderVo sampleOrderVo = sampleOrderService.selectSampleOrderBySampleId(orderId);

//        JslOrderVo jslOrderVo = jslOrderService.selectJslOrderVoByUserIdAndOrderId(orderId, userId);
//        String orderId=reqOrderDetail.getOrderId().substring(0,reqOrderDetail.getOrderId().length()-1);
//        JslOrderVo jslOrderVo = jslOrderMapper.selectJslOrderVoByOrderId(orderId);

        QueryWrapper<JslOrderArrears> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", sampleOrderVo.getSampleId());
        queryWrapper.orderByAsc("create_time");
        List<JslOrderArrears> jslOrderArrears = jslOrderArrearsService.list(queryWrapper);


        List<QueryTrackData> express = new ArrayList<>();
        // 判断当前是否存在物流信息
        if (sampleOrderVo.getLogisticStatus() == 1) {
            QueryTrackParam queryTrackParam = QueryTrackParam.builder().com(sampleOrderVo.getLogisticCode()).num(sampleOrderVo.getLogisticNum()).phone(sampleOrderVo.getPhone()).build();
            QueryTrackResp queryTrackResp = null;
            try {
                queryTrackResp = queryTrackService.queryTrack(queryTrackParam);
                if ("ok".equalsIgnoreCase(queryTrackResp.getMessage()) && "200".equals(queryTrackResp.getStatus())) {
                    express = queryTrackResp.getData();
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error(e);
            }
        }
        JSONObject data = new JSONObject();
        data.put("order", sampleOrderVo);
        data.put("express", express);
        return CommonResult.success(data);
    }


    /**
     * cancelOrderApply: 申请退货<br/>
     *
     * @param reqOrderDetail
     * @param result
     * @return
     * @author Jason.Wang
     * @date 2022/1/1 21:43
     */
    @PostMapping("cancel/apply")
    @CrossOrigin
    public CommonResult cancelOrderApply(@RequestBody @Validated ReqOrderDetail reqOrderDetail, BindingResult result) {
        super.checkBindResult(result);
        JslOrderVo jslOrderVo = jslOrderService.selectJslOrderVoByUserIdAndOrderId(reqOrderDetail.getOrderId(), super.getCurrentUserInfo().getUserId());
        if (jslOrderVo.getOrderStatus() != 1) {
            return CommonResult.success(jslOrderService.updateCancelOrderByOrderIdAndUserIdForApply(jslOrderVo));

        }
        return CommonResult.failed("当前订单不能申请退货退款");
    }

    /**
     * cancelOrder: 取消当前订单信息<br/>
     *
     * @param reqCancelOrder
     * @param result
     * @return
     * @author Jason.Wang
     * @date 2022/1/1 21:43
     */
    @PostMapping("cancel")
    @CrossOrigin
    public CommonResult cancelOrder(@RequestBody @Validated ReqCancelOrder reqCancelOrder, BindingResult result) {
        super.checkBindResult(result);
        JslOrderVo jslOrderVo = jslOrderService.selectJslOrderVoByUserIdAndOrderId(reqCancelOrder.getOrderId(), super.getCurrentUserInfo().getUserId());
        if (null == jslOrderVo || jslOrderVo.getOrderStatus() != 1) {
            return CommonResult.failed("当前订单不能申请退货退款");
        }
        return CommonResult.success(jslOrderService.updateCancelOrderByOrderIdAndUserId(reqCancelOrder, jslOrderVo));
    }


    /**
     * @return com.fxp.project.jiuselu.web.domain.CommonResult
     * @Description 确认收获
     * @Date 14:57 2022/1/3
     * @Param [reqOrderConfirmReceipt, result]
     * @Author M_
     **/
    @PostMapping("/confirmReceipt")
    @CrossOrigin
    public CommonResult confirmReceipt(@RequestBody @Validated ReqOrderConfirmReceipt reqOrderConfirmReceipt, BindingResult result) {
        super.checkBindResult(result);
        String orderId = reqOrderConfirmReceipt.getOrderId();
        if (StringUtils.isBlank(orderId)) {
            return CommonResult.failed("订单号不能为空");
        }
        JslOrder order = jslOrderService.getById(orderId);
        if (order == null) {
            return CommonResult.failed("该订单已不存在");
        }
        if (order.getOrderStatus() == 1) {
            CommonResult.failed("已完成收货,请刷新");
        } else {
            //更新为已支付
            jslOrderService.orderConfirmReceipt(reqOrderConfirmReceipt);
            //添加佣金
            System.out.println(BaseController.getUser().getUserId() + "---------------------");
            jslUserService.calculateProfit(orderId, BaseController.getUser().getUserId(), new BigDecimal("0"));

            //添加用户消费金额
            JslUser jslUser = jslUserService.getById(BaseController.getUser().getUserId());
            jslUser.setConsumeAmount(jslUser.getConsumeAmount().add(order.getTotalAmount()));
            jslUserService.updateById(jslUser);
        }

        return CommonResult.success("更新成功");
    }


    /**
     * @return com.fxp.project.jiuselu.web.domain.CommonResult
     * @Description 确认收获
     * @Date 14:57 2022/1/3
     * @Param [reqOrderConfirmReceipt, result]
     * @Author M_
     **/
    @PostMapping("/getUserOrderPage")
    @CrossOrigin
    public CommonResult getUserOrderPage(@RequestBody UserOrderQo userOrderQo, BindingResult result) {
        return CommonResult.success(jslOrderService.getUserOrderPage(userOrderQo.getPage(), userOrderQo.getSize(), userOrderQo.getUserId(),userOrderQo.getInviteId()));
    }

    /**
     * @return com.fxp.project.jiuselu.web.domain.CommonResult
     * @Description 获取订单状态
     * @Date 14:57 2022/1/3
     * @Param [reqOrderConfirmReceipt, result]
     * @Author M_
     **/
    @PostMapping("/getOrderStatus")
    @CrossOrigin
    public CommonResult getOrderStatus(@RequestBody OrderStatusQo orderStatusQo, BindingResult result) {
        super.checkBindResult(result);
        Long userId = super.getCurrentUserInfo().getUserId();
        String orderId = orderStatusQo.getOrderId();
        JslOrder jslOrder = jslOrderService.getById(orderId);
        System.out.println(jslOrder.getPayStatus());
        if (jslOrder.getPayStatus() == 1) {
            jslOrderService.aboutApply(orderId,userId);
            BigDecimal userMoney = jslUserService.selectMoneyByUserId(userId);
//            BigDecimal blance = userMoney.subtract(jslOrder.getDeduction());
            BigDecimal blance = null;
            if (Optional.ofNullable(jslOrder.getDeduction()).isPresent()) {
                blance = userMoney.subtract(jslOrder.getDeduction());
            } else blance = new BigDecimal("0.0");
            JslUser jslUser = new JslUser();
            jslUser.setUserId(super.getCurrentUserInfo().getUserId());
            jslUser.setUserMoney(blance);
//            jslUserService.updateById(jslUser);
            jslOrderService.updateOrderType(orderId);
        }
        return CommonResult.success(new OrderStatusVo(jslOrder.getOrderType(), jslOrder.getPayStatus()));
    }

    /**
     * 取消订单
     *
     * @param orderStatusQo
     * @return
     */
    @PostMapping("/upstatus")
    @CrossOrigin
    public CommonResult updateStatus(@RequestBody OrderStatusQo orderStatusQo) {
        return CommonResult.success(jslOrderService.updateStatus(orderStatusQo.getOrderId()));
    }

    @Autowired
    IJslUserFareOrderApplyService jslUserFareOrderApplyService;

    /**
     * 取消订单
     *
     * @param
     * @return
     */
    @PostMapping("/updateFareStatus/{ids}")
    @CrossOrigin
    public CommonResult updateFareStatus(@PathVariable("ids") String[] ids, @RequestBody HashMap map) {
        boolean update = jslOrderService.update(new UpdateWrapper<JslOrder>().in("order_id", ids).set("is_fare", 1));
        List list = new ArrayList<>();
        for (String str : ids) {
            JslUserFareOrderApply jslUserFareOrderApply = new JslUserFareOrderApply();
            jslUserFareOrderApply.setFareApplyId(Long.valueOf(map.get("fareApplyId").toString()));
            jslUserFareOrderApply.setFareId(Long.valueOf(map.get("fareId").toString()));
            jslUserFareOrderApply.setOrderId(str);
            jslUserFareOrderApply.setOrderMoney(jslOrderService.selectJslOrderVoByOrderId(str).getTotalAmount());
            jslUserFareOrderApply.setUserId(super.getCurrentUserInfo().getUserId());
            list.add(jslUserFareOrderApply);
        }
        jslUserFareOrderApplyService.saveBatch(list);
        return CommonResult.success(update);
    }

    @PostMapping("/findByOrderId")
    @CrossOrigin
    public CommonResult findByOrderId(String orderId) {
        orderId = orderId.substring(0, orderId.length() - 1);
        JslOrder byId = jslOrderService.getById(orderId);
        return CommonResult.success(byId);
    }

    /**
     * 延长发货
     *
     * @param orderId
     * @return
     */
    @PostMapping("/isdelay")
    @CrossOrigin
    public CommonResult updateOrderIsdelay(String orderId) {
        JslOrder jslOrder = new JslOrder();
        jslOrder.setOrderId(orderId);
        jslOrder.setIsDelay(1);
        return CommonResult.success(jslOrderService.updateById(jslOrder));
    }
}
